<?php

/*	SQL :
	
CREATE TABLE `cache` (
  `id` int(5) unsigned NOT NULL AUTO_INCREMENT,
  `var` varchar(255) NOT NULL,
  `val` text NOT NULL,
  `death` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `var` (`var`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `variables` (
  `id` int(5) unsigned NOT NULL AUTO_INCREMENT,
  `var` varchar(50) NOT NULL,
  `val` text NOT NULL,
  `last_update` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `var` (`var`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

*/

function get_var($varname) {
	$val = DB::GetOneByQuery("SELECT variables.val FROM variables WHERE variables.var='{$varname}';");
	return $val ? unserialize($val) : false;
}

function set_var($varname, $val) {
	$recid = DB::GetOneByQuery("SELECT id FROM variables WHERE variables.var like '{$varname}';"); 
	if (!$recid) $recid = DB::InsertEmptyRecord("variables");
	if (!$recid) return false; // # I CANNOT GAIN THE RECORD
	$var["id"] = $recid;
	$var["var"] = $varname;
	$var["val"] = serialize($val);
	return DB::Update("variables", $var);
}

function delete_var($varname) {
	return DB::Query("DELETE FROM variables WHERE variables.var like '{$varname}';");
}

function dbcache($varname, $val=null, $delete = false) {
	if ($delete) {
		return DB::Query("DELETE FROM cache WHERE cache.var like '{$varname}';");
	}elseif (!$val) {
		$val = DB::GetOneByQuery("SELECT cache.val FROM cache WHERE cache.var like '{$varname}';");
		return $val ? unserialize($val) : false;		
	}else{
		$recid = DB::GetOneByQuery("SELECT id FROM cache WHERE cache.var like '{$varname}';"); 
		//if (!$recid) $recid = DB::InsertEmptyRecord("cache");
		//if (!$recid) return false; // # I CANNOT GAIN THE RECORD
		if ($recid) $var["id"] = $recid;
		$var["var"] = $varname;
		$var["val"] = serialize($val);
		return ($recid) ? DB::Update("cache", $var) : DB::Insert("cache", $var);
	}
}

?>
